<template lang="pug">
  .addBrand-body
    .addBrand
      .addBrand-container           
        .addBrand-header
          h3 {{title}}
        .addBrand-failure
          span.warning 当前状态： 
          //- span(v-if="ruleForm.reviewStatus == 0") 草稿
          span(v-if="ruleForm.reviewStatus == 1") 审核中
          span(v-if="ruleForm.reviewStatus == 2") 审核通过
          span(v-if="ruleForm.reviewStatus == 3") 审核失败
        el-form(:model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm")
          el-form-item(label="品牌名称:" required)
            el-autocomplete(
              v-model="ruleForm.brandName"
              value-key="name"
              value="id"
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入品牌名称"
              @select="handleSelect"
              @change="changeBrandName"
            ) 
          el-form-item(label="商标注册号:" prop="trademarkRegistrationNumber")
              el-input(v-model="ruleForm.trademarkRegistrationNumber")
          el-form-item(label="品牌公司:" prop="brandCompany")
              el-input(v-model="ruleForm.brandCompany") 
          el-form-item(label="产地:" prop="isImport")
              el-select(v-model="ruleForm.isImport" placeholder="请选择产地") 
                el-option(label="进口" :value="1")
                el-option(label="国产" :value="2")   
          el-form-item(label="证书：" required)
            .el-form-info 证书图片不超过三张，图片大小≤10MB
            .el-form-bd
              el-upload(
                action="#"
                class="upload-demo"
                :multiple="true"
                accept="image/png, image/jpeg, image/jpg"
                ref="businessUpload"
                :show-file-list="false"
                :auto-upload="false"
                :file-list="businessFiles"
                :on-change="handleBusinessChange"
                list-type="picture-card"
              )
                .el-upload-btn(slot="trigger")
                  .iconfont.el-icon-plus
                  .el-upload-btn-txt 点击上传
              .el-form-file(v-if="businessFiles.length")
                .el-form-img(v-for="item, index in businessFiles", :style="{'background-image':`url(${item.url})`}")
                  .iconfont.el-icon-error(@click="delFiles('businessFiles', index)")
              .el-form-file(v-if="ruleForm.brandCertificatelist.length")
                .el-form-img(v-for="item, index in ruleForm.brandCertificatelist", :style="item.fileUrl | filterUrl")
                  .iconfont.el-icon-error(@click="delBusiness(index)")  

          el-form-item(label="品牌logo：" required)
            .el-form-info 仅允许上传一张图片，文件大小≤5MB
            .el-form-bd
              el-upload(
                action="#"
                class="upload-demo"
                :limit="1"
                :multiple="false"
                accept="image/png, image/jpeg, image/jpg"
                ref="hiddenUpload"
                :show-file-list="false"
                :auto-upload="false"
                :on-change="handleLogoChange"   
                :on-exceed="handleGridExceed"             
                list-type="picture-card"
              )
                .el-upload-btn(slot="trigger")
                  .iconfont.el-icon-plus
                  .el-upload-btn-txt 点击上传
              .el-form-file(v-if="logoFiles.length")
                .el-form-img(v-for="item, index in logoFiles", :style="{'background-image':`url(${item.url})`}")
                  .iconfont.el-icon-error(@click="delFiles('logoFiles', index)")
              .el-form-file(v-if="ruleForm.logoUrl")
                .el-form-img(:style="{'background-image':`url(${ruleForm.logoUrl})`}")
                  .iconfont.el-icon-error(@click="delLogoUrl")
    el-card(class="failureReason" v-if="ruleForm.reviewStatus === 3")
      el-form(label-width="100px" )
        el-form-item(label="失败原因:")
          p {{ approvalOption }}  
    el-card 
      el-row(style="display:flex;justify-content:center;")
        el-col(:span="2")
          el-button(size="small" @click="$router.back()") 取消
        el-col(:span="2")
          el-button(size="small" type="primary" @click="save") 确定              
</template>

<script>
import { addSupplierBrand, loadUpdateSupplierBrand,loadManagerSupplierBrands,updateSupplierBrand,addOrUpdateSupplierBrand,FileUpload,saveFileManage } from 'api'
  export default {
    name: 'addnewbrand',
      data(){
        return{
          restaurants: [],
          name: '',
          title: '添加品牌',
          failureReason:'名称不符合规定',
          businessFiles: [],  
          logoFiles: [],  
          brandCertificatelist:[],  
          approvalOption:'',
          ruleForm: {
            brandName: '',
            logoId: '',
            logoUrl: '',
            certificateFileList: '',
            brandCertificatelist: [],
            brandId: '',
            trademarkRegistrationNumber: '',
            brandCompany: '',
            isImport: '',
            supplierBrandId: '',
            approvalOptions: ''
          },
          rules: {
            trademarkRegistrationNumber: [
              { required: true, message: '请输入商标注册号', trigger: 'blur' }
            ],
            brandCompany: [
              { required: true, message: '请输入品牌公司', trigger: 'blur' }
            ],
            isImport: [
              { required: true, message: '请选择产地', trigger: 'blur' },
            ],
          },
        }
      },
      computed: {  
        limit () {
          return 2 - (this.businessFiles.length + this.ruleForm.brandCertificatelist.length)
        },
      },
      methods: {
        querySearchAsync (queryString, cb) {
          var restaurants = this.restaurants
          var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants
          cb(results)
        },
        createStateFilter (queryString) {
          return (name) => {
            return (name.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
          };
        },
        handleSelect (item) {
          this.ruleForm.brandId = item.id
          this.ruleForm.brandName = item.name
          this.ruleForm.trademarkRegistrationNumber = item.trademarkRegistrationNumber
          this.ruleForm.brandCompany = item.brandCompany
          this.ruleForm.isImport = item.isImport
          this.ruleForm.logoUrl = item.fileUrl
          this.ruleForm.logoId = item.logoId
        },
        changeBrandName (value) {
          this.ruleForm.brandId = value
          this.ruleForm.brandName = value
        },
        async initRestaurants () {
          try {
            const { ResultSet } = await this.$axios.post(loadManagerSupplierBrands, this.ruleForm.brandName)
            this.restaurants = ResultSet.Result
          } catch (err) {
            console.log(err)
            this.$message.error(err.message || err.ResultSet.errors)
          }
        },
        filterFileSize (size) {
          return new Promise((resolve, reject) => {
            const defaultSize = 10 //MB
            if (size <= 10 * 1024 * 1024) {
              resolve(true)
            } else {
              resolve(false)
            }
          })
        },
        async handleBusinessChange (file, fileList) {
          console.log(this.businessFiles.length , this.ruleForm.brandCertificatelist.length)
          this.businessFiles = fileList
          if (this.businessFiles.length + this.ruleForm.brandCertificatelist.length > 3) {
            this.businessFiles = fileList.slice(0,3-this.ruleForm.brandCertificatelist.length)
            this.$message.error('最多上传三张证书图片！')
            return
          }   
          const valid = await this.filterFileSize(file.size)
          console.log(valid)
          if (!valid) {
            let index = fileList.findIndex(item => item.uid === file.uid)
            fileList.splice(index,1)
            this.$message.error('图片大小≤10MB！')
            return
          }             
        },       
        delFiles (key, index) {
          this[key].splice(index, 1)
        },
        delCertificate (index) {
          this.supplierQualificationList.splice('index', 1)
        },
        delBusiness (index) {
          console.log(this.ruleForm.brandCertificatelist)
          console.log(this.businessFiles)
          this.ruleForm.brandCertificatelist.splice(index, 1)
        },
        async handleLogoChange (file, fileList) {
          const valid = await this.filterFileSize(file.size)
          if (!valid) {
            let index = fileList.findIndex(item => item.uid === file.uid)
            fileList.splice(index,1)
            this.$message.error('图片大小≤5MB！')
            return
          }
          this.ruleForm.logo = ''
          this.ruleForm.logoUrl = ''
          this.logoFiles = fileList
          console.log(this.logoFiles)
        },
        delLogoUrl () {
          this.ruleForm.logo = ''
          this.ruleForm.logoUrl = ''
        },
        handleGridExceed () {
          this.$message.error('最多只能上传1张Logo！')
        },
        async fileUpload (raw) {
          console.log(raw)
          console.log(this.businessFiles.length,this.ruleForm.brandCertificatelist.length)     
          // this.ruleForm.brandCertificatelist.slice(0,3)    
          console.log(this.ruleForm.brandCertificatelist)
          return new Promise(async (resolve, reject) => {
            try {
              let formData = new FormData()
              formData.append('Filedata', raw)
              formData.append("applicationId", 4)
              const { ResultSet } = await this.$axios.post(FileUpload, { formData: formData, isUpload: true }, { headers:{ "Content-Type": "multipart/form-data" } })
              resolve({ ...ResultSet.Result[0] })
            } catch (err) {
              console.log(err)
              reject(err)
            }
          })
        },       
        async save () {
          if (!this.ruleForm.brandName) {
            this.$message.error('请填写或选择品牌！')
            return
          }
          if (!this.businessFiles.length && !this.ruleForm.brandCertificatelist.length) {
            this.$message.error('请先上传证书图片！')
            return
          }
          if (!this.logoFiles.length && !this.ruleForm.logoUrl) {
            this.$message.error('请先上传品牌logo！')
            return
          }
          const loading = this.$loading({
            text: '上传中',
          })
          if (this.businessFiles.length) {           
            console.log(this.ruleForm.brandCertificatelist)
            let fileList = await Promise.all(this.businessFiles.map(async (item) => {
              try {
                const file = await this.fileUpload(item.raw)
                return { fileUrl: file.fileUrl, fileId: file.fileId }
              } catch (err) {
                console.error('error: ' + JSON.stringify(err))
              }
            }))
            this.ruleForm.brandCertificatelist.push(...fileList)
            this.businessFiles = []
            this.$refs.businessUpload.clearFiles()
            console.log(this.businessFiles)
            console.log(this.ruleForm.brandCertificatelist)
          }
          if (this.logoFiles.length) {
            const logoFile = await this.fileUpload(this.logoFiles[0].raw)
            this.ruleForm.logoId = logoFile.fileId
            this.ruleForm.logoUrl = logoFile.fileUrl
          }
          this.$refs.ruleForm.validate(async (valid) => {
            try {
              if (valid) {
                let query = { ...this.ruleForm }
                query.certificateFileList = query.brandCertificatelist.map(item => item.fileId).join(',')
                await this.$axios.post(addOrUpdateSupplierBrand, { content: { ...query } })
                loading.close()
                this.$router.back()
              } else {
                this.$message.error('请仔细检查信息是否有误！')
              }
            } catch (err) {
              loading.close()              
              console.log(err)
              this.$message.error(err.message || err.ResultSet.errors)
            }
          })
        },
        async getDetail () {
          try {
            const { ResultSet } = await this.$axios.post(loadUpdateSupplierBrand, { content: { supplierBrandId: this.$route.params.id } })
            let form = { ...ResultSet.userData }
            this.ruleForm = { ...this.ruleForm, ...form.supplierBrand }
            this.ruleForm.brandName = form.supplierBrand.name
            this.ruleForm.brandCertificatelist = form.brandCertificatelist || []
            console.log(this.ruleForm.brandCertificatelist)
            this.approvalOption = form.approvalList.approvalOptions
          } catch (err) {
            console.log(err)
            this.$message.error(err.message || err.ResultSet.errors)
          }
        }
      },
      beforeRouteEnter (to, from, next) {
        // ...
        next(vm => {
          vm.initRestaurants()
          if (to.params.id) {
            vm.title = '编辑品牌'  
            vm.getDetail()            
          } else {
            vm.title = '添加品牌'
          }
        })
      },
      // mounted() {
      //   this.restaurants = this.loadAll();
      // }
  }
</script>
<style type="text/css" lang="scss">
.upload-demo {
  .el-upload--picture-card {
    width: 98px;
    height: 98px;
    line-height: 1;
  }
  .el-upload-btn-txt {
    margin-top: 15px;
  }
}

</style>

<style scoped lang="scss" scoped>
  .addBrand-body {
      padding: 0 32px 16px;
  }
  .addBrand {
    background: #FFFFFF;
    border-radius: 4px;
    padding-bottom:20px;
    margin-bottom:20px;
  }
  .addBrand-container {
    padding: 20px;
  }
 
  .addBrand-header h3{
        font-weight:bold;
        font-size:16px;
    }
  .list-header-filter{
      padding:20px 20px 0;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    border: 1px dashed #d9d9d9;
    font-size: 28px;
    color: #8c939d;
    width: 110px;
    height: 110px;
    line-height: 110px;
    text-align: center;
  }
  .avatar {
    width: 110px;
    height: 110px;
    display: block;
  }
 
//   上传图片样式
    .upload-form-bd {
    padding:0 20px 20px;
    margin-bottom: 20px;
    background: #fff;
    padding-bottom: 50px;
    transition: all .5s;
    }
    .form-item {
  display: flex;
  align-items: center;
  margin-top: 15px;
  font-size: 12px;
  color: #333333;
  &.form-item-start {
    align-items: flex-start;
    .form-item-label {
      line-height: 60px;
      margin-right: 20px;
    }
  }
  &.spec-sku {
    .form-item-label {
      line-height: 20px;
      margin-right: 20px;
    }
  }
  &.form-item-top {
    align-items: flex-start;
  }
  & .form-item-body {
    display: flex;
    align-items: center;
    width: 1000px;
  }
  & .form-item-label {
    min-width: 100px;
    text-align: right;
    // margin-right: 10px;
    padding-right: 3px;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: #333333;
    line-height: 20px;
    &.form-item-label_import {
      &:before {
        content: '*';
        color: #F56C6C;
      }
    }
    &.form-item-label_strong {
      font-weight: 600;
      font-size: 14px;
    }
  }
  & .form-item-bd {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-left: 5px;
    min-width: 340px;
    & .el-checkbox-group {
      margin-right: 40px;
      & .el-checkbox {
        margin-right: 20px;
      }
    }
    & .form-item-bd_input {
      display: flex;
      min-width: 130px;
      margin-bottom: 6px;
      height: 40px;
      line-height: 40px;
      padding-left: 21px;
      align-items: center;
      & .el-input {
        width: 200px;
        margin-right: 10px;
      }
      & .form-item-bd_input-value {
        color: #0f73e6;
        cursor: pointer;
        text-decoration: underline;
      }
    }
  }
  & .form-item-bd_setting {
    display: flex;
    align-items: center;
    margin-left: 5px;
    margin-right: 10px;
    width: 150px;
    max-width: 150px;
  }
}
.form-item-bd-info {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #999999;
  line-height: 20px;
}
.el-upload{
    width:110px!important;
    height:110px!important;
}
.demo-ruleForm{
  margin-top: 24px;
}
.el-form-item{
    width:520px;
    .el-select{
      width:100%;
    }
}
.addBrand-failure{
  height: 40px;
  line-height: 40px;
  margin-top: 24px;
  background: #FFF0F1;
  border-top: 1px solid #CBCBCB;
  margin-right: 20px;
  padding-left: 25px;
  span {
    color:#FF2E42;
    font-weight:bold;
    &.warning {
      color:#9C9DA1
    }
  }
}
.failureReason{
  margin-bottom:25px;
}
.el-upload--picture-card {
  width: 96px!important;
  height: 96px!important;
  line-height: 1;
  border: none;
}
.el-form-info {
  font-size: 14px;
  color: #AFAFAF;
}
.el-form-bd {
  margin-top: 15px;
  display: flex;
}
.el-upload-btn {
  width: 96px;
  height: 96px;
  background: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  color: #FF2E42;
  .iconfont {
    font-size: 20px;
    font-weight: bold;
  }
  .el-upload-btn-txt {
    font-size: 14px;
  }
}
.el-form-file {
  display: flex;
  align-items: center;
  .el-form-img {
    position: relative;
    width: 96px;
    height: 96px;
    background-position: center;
    background-repeat: no-repeat;
    background-size: cover;
    margin-left: 16px;
    border-radius: 4px;
    .iconfont {
      position: absolute;
      top: 0;
      right: 0;
      transform: translate(50%, -50%);
      cursor: pointer;
    }
  }
}
.el-autocomplete{
  width:100%;
}
</style>